import {
  _decorator,
  Component,
  Node,
  Input,
  EventTouch,
  input,
  __private,
  Vec2,
  Vec3,
  UITransform,
} from "cc";
const { ccclass, property } = _decorator;

@ccclass("JoyStickManager")
export class JoyStickManager extends Component {
  private body: Node;
  private stick: Node;
  private defaultPos: Vec2;
  private radius: number;

  playerInput: Vec2 = Vec2.ZERO;

  onLoad(): void {
    this.body = this.node.getChildByName("Body");
    this.stick = this.body.getChildByName("Stick");
    this.radius = this.body.getComponent(UITransform).contentSize.width / 2;

    this.defaultPos = new Vec2(
      this.body.getPosition().x,
      this.body.getPosition().y
    );

    input.on(Input.EventType.TOUCH_START, this.onTouchStart, this);
    input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);
    input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this);
  }

  protected onDestroy(): void {
    input.off(Input.EventType.TOUCH_START, this.onTouchStart, this);
    input.off(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);
    input.off(Input.EventType.TOUCH_END, this.onTouchEnd, this);
  }

  start() {}

  onTouchStart(event: EventTouch) {
    // console.log(event.getLocation()); // Location on screen space
    // console.log(event.getUILocation()); // Location on UI space

    this.body.setPosition(event.getLocation().x, event.getLocation().y);
  }

  onTouchMove(event: EventTouch) {
    const eventPos = event.getLocation();

    let stickPos = new Vec2(
      eventPos.x - this.body.position.x,
      eventPos.y - this.body.position.y
    );

    if (stickPos.length() > this.radius) {
      stickPos.multiplyScalar(this.radius / stickPos.length());
    }

    this.stick.setPosition(stickPos.x, stickPos.y);

    this.playerInput = stickPos.clone().normalize();

    // console.log(this.playerInput);
  }

  onTouchEnd() {
    this.body.setPosition(this.defaultPos.x, this.defaultPos.y);
    this.stick.setPosition(0, 0);

    this.playerInput = Vec2.ZERO;
  }

  update(deltaTime: number) {}
}
